<template>
    <div class="container" ref="container">
        <div class="spin" v-show="spinning">
            <a-spin size="large" :spinning="spinning" />
        </div>

        <v-stage :config="configKonva" ref="stage" class="stage">
            <v-layer ref="layer">

            </v-layer>
        </v-stage>

        <div class="typeToolBox" v-show="!showTypeBox" @click="toggleShowTypeBox">
            <img src="@/assets/img/m_projectBoard/icon_lei.png" /> <span>操作</span>
        </div>

        <transition name="slide-fade">
            <div class="typeBox" v-show="showTypeBox">
                <div class="typeBoxContent">
                <div style="font-size: 14px;font-weight: 500; text-align: center;margin-bottom: 24px;">切换可视化测点图</div>
                <a-row class="boardList">
                    <a-col :span="24">
                        <a-dropdown>
                            <a-menu :disabed="!drawingBoardList.length" slot="overlay" @click="changeBoard">
                                <a-menu-item :key="b.id" v-for="b in drawingBoardList">
                                    {{b.name}}
                                </a-menu-item>
                            </a-menu>
                            <a-button style="width: 100%"> {{selectedDrawingBoardName ? selectedDrawingBoardName : '选择测点图'}} <a-icon type="down" /> </a-button>
                        </a-dropdown>
                    </a-col>
                </a-row>
                <a-row class="typeHeader">
                    <a-col :span="20"><div class="headerBar"></div><div class="typeTitle">图层选择</div></a-col>
                    <a-col :span="4"><span class="typeSelectAll" @click="toggleShowAllType">全选</span></a-col>
                </a-row>

                <div class="typesList">
                    <a-row v-for="t in types" :key="t.id" class="typeRow">
                        <a-row  >
<!--                            <a-col :span="3">-->
<!--                                -->
<!--                            </a-col>-->
                            <a-col :span="21" @click="toggleShowType(t)">
                                <img :src="getDeviceIcon(t.id)" class="typeImage" />{{t.name}}
                            </a-col>
                            <a-col :span="3" @click="toggleShowType(t)">
                                <img v-if="t.show"  src="@/assets/img/m_projectBoard/icon_right_blue.png" class="typeCheckImg" />
                                <img v-else src="@/assets/img/m_projectBoard/icon_right_grey.png" class="typeCheckImg" />
                            </a-col>
                        </a-row>
                    </a-row>
                </div>
                <div class="btnBox">
                    <button @click="closeShowTypeBox">确 定</button>
                </div>
                </div>
            </div>
        </transition>

        <div class="scaleBox" v-show="!showTypeBox">
            <div @click="scaleUp">
                <img v-if="enableScaleUp" src="@/assets/img/m_projectBoard/icon_scale_up.png" />
                <img v-else src="@/assets/img/m_projectBoard/icon_scale_up_grey.png" />
            </div>
            <div @click="scaleDown">
                <img v-if="enableScaleDown" src="@/assets/img/m_projectBoard/icon_scale_down.png" />
                <img v-else src="@/assets/img/m_projectBoard/icon_scale_down_grey.png" />
            </div>
        </div>

        <div class="summaryBox" v-show="!showTypeBox">
            <div class="summaryItem">
                <div class="num num-error">{{deviceSummary.error}}</div>
                <div class="text">测点异常</div>
            </div>
            <div class="summaryItem">
                <div class="num num-warning">{{deviceSummary.warning}}</div>
                <div class="text">测点报警</div>
            </div>
            <div class="summaryItem">
                <div class="num num-normal">{{deviceSummary.normal}}</div>
                <div class="text">测点核实</div>
            </div>
            <div class="summaryItem">
                <div class="num num-success">{{deviceSummary.success}}</div>
                <div class="text">测点正常</div>
            </div>
        </div>

        <div ref="deviceTooltip" @click="goPointDetail(tooltipPoint)" class="device-tooltip" :class="'device-tooltip-' + tooltipPoint.status">
            <div v-if="tooltipPoint.normal">
                <div>{{tooltipPoint.normal}}</div>
                <div class="device-tooltip-remark">{{tooltipPoint.value6}}</div>
            </div>
            <div v-else style="height: 42px; line-height: 42px">
                没有数据
            </div>

        </div>
    </div>
</template>

<script>
    import {
        login,
    } from "@/request/api";
    import md5 from 'js-md5';

    import {Board} from '@/utils/drawingBoard/board'
    import axios from 'axios'
    import {getDeviceIconByType} from '@/utils/drawingBoard/drawIcon'
    export default {
        name: "m_projectBoard",
        computed: {
            cid: function () {
                return this.$route.query.cid;
            },
            deviceSummary: function() {
                // return  {
                //     error: this.pointDataList.filter(i => i.status === 'error').length,
                //     warning: this.pointDataList.filter(i => i.status === 'warning').length,
                //     normal: this.pointDataList.filter(i => i.status === 'error').length,
                //     success: this.pointDataList.filter(i => i.status === 'success').length,
                // }
                return  {
                    error: this.statusSummary.abnormal,
                    warning: this.statusSummary.alert,
                    normal: this.statusSummary.verify,
                    success: this.statusSummary.normal,
                }

            },
        },
        data() {
            return {
                spinning: false,
                types: [],
                devices: [],
                pointDataList: [],
                selectedDrawingBoardId: null,
                selectedDrawingBoardName: '',
                drawingBoardList: [],
                tooltipPoint: {
                    value1: '',
                    value6: '',
                    single: '',
                    sum: '',
                    status: '',

                },
                configKonva: {
                    width: 0,
                    height: 0
                },
                clientWidth: 0,
                clientHeight: 0,
                scaleRate: 1.0,
                showTypeBox: false,
                showAllType: true,
                enableScaleUp: true,
                enableScaleDown: true,
                transitionName: 'slide-left',
                statusSummary: {

                }
            }
        },
        async created() {

        },
        async mounted() {
            let isPreview = this.$route.query.isPreview; // 后台预览标记
            if(!isPreview) {
                let {data} = await login({
                    userName: "18688793445",
                    passWord: md5("guangliantest"),
                });
                if (data.code == 200) {
                    localStorage.setItem('token', data.result.token)
                }
            }

            const stage = this.$refs.stage.getNode()
            const layer = this.$refs.layer.getNode()
            // console.log(deviceRemarkBox)
            this.board = new Board(stage, layer, null, null);

            // this.clientWidth = this.$refs.container.clientWidth;
            // this.clientHeight = this.$refs.container.clientHeight;
            this.clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
            this.clientHeight = document.documentElement.clientHeight || document.body.clientHeight;

            // this.getPointsList()
            this.loadDrawing();
        },

        methods: {
            loadDrawing() {
                this.drawingBoardList = [];
                this.spinning = true;
                axios.get(`/guanglian/pointFigure/queryPointFigureByProId/${this.cid}`).then( res => {
                    this.spinning = false;
                    if(res.data.code != 200) {
                        this.$message.error('获取测点图数据失败');
                        return
                    }
                    let data = res.data.result;
                    if(!data.length) {
                        this.$message.info('没有可视化测点图');
                        return;
                    }
                    for(let p_data of data) {
                        // 测点图信息
                        this.drawingBoardList.push({
                            id: p_data.id,
                            name: p_data.pointFigureName,
                            gaugePointList: p_data.gaugePointList,
                            pointList: p_data.pointList,
                            drawingInfo: p_data.drawingInfo,
                            reproduction: p_data.reproduction, // 底图
                        })
                    }
                    this.changeBoard({key: 0})
                })
            },

            initDrawing() {
                this.selectedDrawingBoardName = ''
                this.selectedDrawingBoardId = null;
                const layer = this.$refs.layer.getNode()
                layer.destroyChildren()
                layer.draw()
            },

            changeBoard({key}) {
                console.log('key', key)
                console.log('drawingBoardList', this.drawingBoardList)
                if(!this.drawingBoardList.length) {
                    this.devices = []
                    return;
                }
                let p_data;
                if(key == 0) {
                    p_data = this.drawingBoardList[0]
                }
                else {
                    this.initDrawing();
                    p_data = this.drawingBoardList.find(i => i.id == key);
                }

                this.bindTypesAndDevice(p_data);
                this.loadDeviceData();
                this.loadDeviceStatusSummary();
            },

            bindTypesAndDevice(p_data) {
                let types_in_board = [];
                this.devices = [];
                this.types = [];
                if(p_data) {

                    if(p_data.gaugePointList) {
                        for (let g of p_data.gaugePointList) {
                            let _type = {
                                id: g.monitorId,
                                type: g.monitorId,
                                name: g.monitorName,
                                icon_base64: `t_id_${g.monitorId}`,
                                show: true,
                            }
                            this.types.push(_type)

                            for(let d of g.pointList) {
                                let _device = {
                                    id: d.pid,
                                    name: d.pointName,
                                    eqId: d.eqId,
                                    type: g.monitorId,
                                    show: false,
                                    draw: false,
                                    pointData: {
                                        normal: '',
                                        status: '',
                                        single: '',
                                        sum: '',
                                    }
                                }
                                if(p_data.pointList.indexOf(d.pid) >=0)
                                    this.devices.push(_device);
                            }
                        }
                    }

                    // console.log(this.devices)

                    this.selectedDrawingBoardId = p_data.id
                    this.selectedDrawingBoardName = p_data.name
                    this.board.recoverDrawForMobile(
                        p_data, this.clientWidth, this.clientHeight,
                        (sharp) => {
                            if (sharp.attrs._meta && sharp.attrs._meta.type === 'device') {
                                types_in_board.push(sharp.attrs._meta.type_id)
                                let device_id = sharp.attrs._meta.device_id;
                                this.bindDeviceEvent(device_id);
                                // this.board.setDeviceTextColor(sharp.attrs._meta.device_id, 'rgb(255, 71, 68)')
                            }
                        }
                    );

                    // stage 点击事件
                    this.board.stage.on('tap click dragmove', () => {
                        let deviceTooltip = this.$refs.deviceTooltip;
                        // console.log(222)
                        deviceTooltip.style.display = 'none';
                    })
                }
                if(types_in_board.length > 0) {
                    this.types = this.types.filter(t => types_in_board.includes(t.id)) || []
                }
            },

            bindDeviceEvent(device_id) {
                let deviceNode = this.board.layer.findOne('#deviceGroup-' + device_id);
                if(!deviceNode) return;
                deviceNode.on('tap click', (e) => {
                    e.cancelBubble = true;
                    let deviceTooltip = this.$refs.deviceTooltip;

                    this.tooltipPoint = this.pointDataList.find(p => p.pointId == deviceNode.attrs._meta.device_id) || {}
                    if(!this.tooltipPoint || !this.tooltipPoint.normal) {
                        // 没有数据不显示
                        return;
                    }
                    deviceTooltip.style.visibility = 'hidden';
                    deviceTooltip.style.display = 'initial';
                    this.$nextTick(() => {
                        // 等dom更新
                        deviceTooltip.style.top = deviceNode.absolutePosition().y - deviceTooltip.offsetHeight + 8 + 'px';
                        deviceTooltip.style.left = deviceNode.absolutePosition().x - 28 + 'px';
                        deviceTooltip.style.visibility = 'visible'
                    })


                    // this.tooltipPoint = this.pointDataList[0];
                });
            },
            loadDeviceData() {
                // 测点读数和告警信息
                this.pointDataList = [];
                let eqIdList = this.devices.map(i => i.eqId);
                if(!eqIdList.length) return;
                let params = eqIdList.join(',')
                let updatedPointId = {};
                axios.get(`/guanglian/warningInfo/getstatus?eqIdList=${params}`).then( res => {
                    let _data = res.data.result;
                    for(let d of _data) {
                        let pointData = {
                            pointName: d.pointName,
                            eqId: d.eqId,
                            pointId: d.pointId,
                            status: 'default',
                            normal: parseFloat(d.value1),
                            value6: parseFloat(d.value6),
                            single: parseFloat(d.single),
                            sum: parseFloat(d.sum),

                        }
                        let _value6 = isNaN(pointData.value6) ? pointData.value6 : pointData.value6.toFixed(2);
                        pointData.value6 =  '' + _value6 + ' ' + (d.unit ? d.unit : '')
                        let _normal = isNaN(pointData.normal) ? pointData.normal : pointData.normal.toFixed(2);
                        pointData.normal = '' + _normal + ' ' + (d.unit ? d.unit : '')


                        let text_color = 'rgba(0, 0, 0, 1)';
                        let display_warning = false;

                        if(d.oneIsWarring == '告警' || d.sumIsWarring == '告警') {
                            pointData.status = 'warning'
                            text_color = 'rgb(254, 168, 4)';
                            display_warning = true;
                        }
                        else if(d.status == 3) {
                            pointData.status = 'error'
                            text_color = 'rgb(255, 71, 68)';
                            display_warning = true;
                        }
                        else if(d.status == 1) {
                            pointData.status = 'success'
                            text_color = 'rgb(77, 214, 166)';
                        }
                        else {
                            // 测点解除
                            pointData.status = 'normal'
                            text_color = 'rgb(55, 114, 255)';
                        }

                        if(!updatedPointId[d.pointId]) {
                            updatedPointId[d.pointId] = true;
                            this.board.setDeviceTextColor(pointData.pointId, text_color, display_warning)
                        }
                        this.pointDataList.push(pointData)
                    }
                })
            },

            loadDeviceStatusSummary() {
                // 测点状态统计
                axios.get(`/guanglian/warningInfo/getResult?proId=${this.cid}`).then( res => {
                    this.statusSummary = res.data.result
                });
            },

            scaleUp(){
                if(!this.enableScaleUp) return;

                this.enableScaleDown = true;
                this.scaleRate += 0.15;
                if(this.scaleRate >= 1.45) {
                    // this.$message.info('已达到最大缩放比例')
                    this.enableScaleUp = false;
                }
                this.board.scaleMobile(this.scaleRate)
            },
            scaleDown() {
                if(!this.enableScaleDown) return;

                this.enableScaleUp = true;
                this.scaleRate -= 0.15;
                if(this.scaleRate <= 0.45) {
                    // this.$message.info('已达到最小缩放比例')
                    this.enableScaleDown = false;
                }
                this.board.scaleMobile(this.scaleRate)
            },
            getDeviceIcon(typeId) {
                return getDeviceIconByType(typeId)
            },
            closeShowTypeBox() {
                this.toggleShowTypeBox()
                console.log(this.types)
                for(let t of this.types) {
                    for(let d of this.devices) {
                        if(d.type != t.id) {
                            continue;
                        }

                        let deviceNode = this.board.layer.findOne('#deviceGroup-' + d.id);
                        this.board.showDevice(deviceNode, t.show)
                    }
                }
                this.board.layer.batchDraw()
            },
            toggleShowTypeBox() {
                if(!this.drawingBoardList.length) {
                    this.$message.info('没有测点图信息')
                    return;
                }
                this.transitionName = this.showTypeBox ? 'slide-right': 'slide-left'
                this.showTypeBox = !this.showTypeBox
            },
            toggleShowType(t) {
                t.show = !t.show;
                console.log(t)
                console.log(this.types)
            },
            toggleShowAllType() {
                this.showAllType = !this.showAllType
                for(let t of this.types) {
                    t.show = this.showAllType
                }
            },
            goPointDetail(pointData) {
                this.$router.push({path: '/m_pointData', query: {proId: this.cid, pointName: pointData.pointName}})
            }
        }
    }
</script>

<style scoped lang="less">
    body {
        margin: 0;
        padding: 0;
        overflow: hidden;
    }
    .container {
        height: 100%;
        /*width: 100%;*/
        /*margin: 0;*/
        /*padding: 0;*/
        /*overflow: hidden;*/
    }

    .spin {
        position: absolute;
        top: 50%;
        left: 50%;
        /*background-color: red;*/
        transform: translate(-50%, -50%);
    }
    .typeToolBox {
        color: #1890ff;
        background-color: #fff;
        border-bottom-left-radius: 5px;
        border-top-left-radius: 5px;
        position: absolute;
        top: 100px;
        right: 0;
        width: 62px;
        height: 36px;
        line-height: 36px;
        font-size: 14px;
        padding: 0 5px;

        img {
            /*margin-top: 10px;*/
            height: 16px;
            width: 16px;
        }
        span {
            display: inline-block;
            margin-left: 2px;
            height: 36px;
            line-height: 36px;
        }
    }
    .typeBox {
        position: absolute;
        top: 0;
        right: 0;
        width: 100%;
        height: 100%;
        z-index: 999;
        background-color: rgba(100, 100, 100, 0.4);
        .typeBoxContent {
            padding: 20px 6px 0 6px;
            background-color: #fff;
            border-bottom-left-radius: 5px;
            border-top-left-radius: 5px;
            position: absolute;
            top: 0;
            right: 0;
            width: 250px;
            height: 100%;
        }
        .boardList {
            margin-bottom: 20px;
        }
        .boardList /deep/ .ant-btn {
            border: none;
        }
        .typesList {
            overflow-x: hidden;
            overflow-y: hidden;
        }
        .btnBox {
            position: absolute;
            bottom: 40px;
            left: 0;
            right: 0;
            /*overflow: hidden;*/
            width: 60px;
            margin: 0 auto;
            /*margin-right: -100px;*/
            /*margin: auto;*/
            button {
                color: #fff;
                background-color: rgb(37, 111, 255);
                border-color: rgb(37, 111, 255);
                border-radius: 5px;
                width: 72px;
                outline: 0;
                box-shadow: none;
            }
        }
        .typeRow {
            margin-top: 8px;
            font-size: 13px;

            .typeImage {
                width: 17px;
                height: 17px;
                margin: 2px 5px 4px 2px;
            }
            .typeCheckImg {
                width: 17px;
                height: 17px;
            }
        }
        .typeHeader {
            .typeTitle {
                padding-left: 6px;
                display: inline-block;
                height: 21px;
                line-height: 21px;
                float: left;
                /*border-left: #1890ff 4px solid;*/
                /*border-radius: 4px;*/
            }
            .headerBar {
                display: inline-block;
                width: 5px;
                height: 14px;
                margin-top: 4px;
                background-color: #1890ff;
                border-radius: 4px;
                float: left;
            }
            .typeSelectAll {
                color: rgb(88, 143, 246);
            }
        }

    }

    .scaleBox {
        position: absolute;
        bottom: 60px;
        right: 6px;
        width: 40px;
        height: 80px;
        background-color: #fff;
        padding: 0 8px;
        border-radius: 6px;
        div {
            height: 40px;
            line-height: 40px;
        }
        img {
            width: 24px;
            height: 24px;
        }
    }

    .summaryBox {
        position: absolute;
        top: 100px;
        left: 6px;
        width: 65px;
        /*height: 240px;*/
        background: transparent;
        .summaryItem {
            margin-bottom: 18px;
            .num {
                border-radius: 5px;
                height: 24px;
                line-height: 24px;
                color: #fff;
                text-align: center;
                margin: 0 auto;
            }
            .num-success {
                background-color: rgb(77, 214, 166);
            }
            .num-error {
                background-color: rgb(255, 71, 68);
            }
            .num-normal {
                background-color: rgb(55, 114, 255);
            }
            .num-warning {
                background-color: rgb(254, 168, 4);
            }
            .text {
                margin-top: 5px;
                text-align: center;
                font-size: 13px;
            }
        }
    }

    .device-tooltip {
        display: none;
        position: absolute;
        width: 110px;
        /*height: 64px;*/
        padding: 6px 4px;
        /*background-color: #f00;*/
        background-color: rgba(255, 255, 255, 0.82);
        box-shadow: 0 0 3px grey;
        border-radius: 6px;
        z-index: 990;
        text-align: center;
        font-size: 12px;
    }
    .device-tooltip-remark {
        vertical-align: middle;
    }
    .device-tooltip-default {
        color: rgb(0, 0, 0);
    }
    .device-tooltip-error {
        color: rgb(255, 71, 68);
    }
    .device-tooltip-warning {
        /*color: rgb(254, 168, 4);*/
        color: rgb(255, 71, 68);
    }
    .device-tooltip-normal {
        /*color: rgb(55, 114, 255);*/
        color: rgb(0, 0, 0);
    }
    .device-tooltip-success {
        /*color: rgb(77, 214, 166);*/
        color: rgb(0, 0, 0);
    }

    .device-tooltip:after{
        content:'';
        position:absolute;
        /*border:10px  solid transparent;*/
        /*border-top-color:gray;*/
        left: 50%;
        top:100%;
        /*left:20px;*/
        margin-left: -5px;
        border-width: 6px;
        border-style: solid;
        /*border-color: rgba(255,255,255, 0.82) transparent transparent transparent;*/
        border-color: rgb(225, 225, 225) transparent transparent transparent;
    }

    .slide-fade-enter-active {
        transition: all .3s ease-in	;
    }
    .slide-fade-leave-active {
        transition: all .4s ease-in-out;
    }
    .slide-fade-enter, .slide-fade-leave-to
        /* .slide-fade-leave-active for below version 2.1.8 */ {
        /*transform: translateX(10px);*/
        opacity: 0;
    }

</style>
